package com.shuyu.web.controller.platform;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.shuyu.common.core.controller.BaseController;
import com.shuyu.common.core.domain.AjaxResult;
import com.shuyu.common.core.page.TableDataInfo;
import com.shuyu.common.exception.ServiceException;
import com.shuyu.common.utils.SecurityUtils;
import com.shuyu.domain.ApprovalAuthorize;
import com.shuyu.domain.ApprovalProcessDetail;
import com.shuyu.domain.ApprovalProcessFlow;
import com.shuyu.service.ApprovalAuthorizeService;
import com.shuyu.service.ApprovalProcessDetailService;
import com.shuyu.service.ApprovalProcessFlowService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 审批流程相关
 * 
 * @author
 */
@RestController
@RequestMapping("/platform/approvalAuthorize")
@Api(tags = "审批授权管理")
public class PApprovalAuthorizeController extends BaseController
{
    @Resource
    private ApprovalAuthorizeService approvalAuthorizeService;


    @PreAuthorize("@ss.hasPermi('system:approvalAuthorize:list')")
    @GetMapping("/list")
    @ApiOperation("查询审批授权列表")
    public TableDataInfo list()
    {
        startPage();
        List<ApprovalAuthorize> list = approvalAuthorizeService.getList();
        return getDataTable(list);
    }
    @PreAuthorize("@ss.hasPermi('system:approvalAuthorize:add')")
    @PostMapping
    @ApiOperation("添加审批授权")
    public AjaxResult add(@RequestBody ApprovalAuthorize approvalAuthorize)
    {
        Long userId = SecurityUtils.getLoginUser().getUserId();
        checkAuthorize(approvalAuthorize, userId);
        approvalAuthorize.setUserId(userId);
        approvalAuthorize.setStatus(0);
        approvalAuthorize.setCreateTime(new Date());
        return toAjax(approvalAuthorizeService.save(approvalAuthorize));
    }

    @PreAuthorize("@ss.hasPermi('system:approvalAuthorize:add')")
    @PutMapping
    @ApiOperation("修改审批授权")
    public AjaxResult update(@RequestBody ApprovalAuthorize approvalAuthorize)
    {
        Long userId = SecurityUtils.getLoginUser().getUserId();
        checkAuthorize(approvalAuthorize, userId);
        approvalAuthorize.setModifyTime(new Date());
        return toAjax(approvalAuthorizeService.updateById(approvalAuthorize));
    }
    private void checkAuthorize(ApprovalAuthorize approvalAuthorize, Long userId){
        //一个类型在当前时间段只能授权给一个人
        LambdaQueryWrapper<ApprovalAuthorize> queryWrapper = new LambdaQueryWrapper<ApprovalAuthorize>().eq(ApprovalAuthorize::getUserId, userId)
                .eq(ApprovalAuthorize::getStatus, 0).ge(ApprovalAuthorize::getAuthorizeEndTime, new Date());
        if(approvalAuthorize.getAuthorizeType() != 0){
            queryWrapper.and(query -> query.eq(ApprovalAuthorize::getAuthorizeType, 0).or().eq(ApprovalAuthorize::getAuthorizeType, approvalAuthorize.getAuthorizeType()));
        }
        if(approvalAuthorize.getId() != null){
            queryWrapper.ne(ApprovalAuthorize::getId,approvalAuthorize.getId());
        }
        int count = approvalAuthorizeService.count(queryWrapper);
        if(count>0){
            throw new ServiceException("有效期内只能授权给一个人，请先取消后再重新授权");
        }
    }

    @PreAuthorize("@ss.hasPermi('system:approvalAuthorize:cancel')")
    @PutMapping("/cancel/{id}")
    @ApiOperation("取消审批授权")
    public AjaxResult cancel(@PathVariable int id)
    {
        ApprovalAuthorize approvalAuthorize = new ApprovalAuthorize();
        approvalAuthorize.setCancelTime(new Date());
        approvalAuthorize.setStatus(1);
        approvalAuthorize.setId(id);
        return toAjax(approvalAuthorizeService.updateById(approvalAuthorize));
    }
    @PreAuthorize("@ss.hasPermi('system:approvalAuthorize:detail')")
    @PutMapping("/{id}")
    @ApiOperation("查看审批授权详情")
    public AjaxResult detail(@PathVariable int id)
    {
        return AjaxResult.success(approvalAuthorizeService.getById(id));
    }
}
